import { useReducer, useContext, useRef, useCallback, useEffect } from 'react';
import { MyContext, State } from './MyContext';

type Selector = (state: State) => any;

export const useSelector = (selector: Selector) => {
    // 强制更新
    const [, forceRender] = useReducer((v) => v + 1, 0);
    const store = useContext(MyContext);

    // 获取当前使用的 state
    const selectedStateRef = useRef(null);
    selectedStateRef.current = selector(store.getState());

    // 对比更新回调
    const checkForUpdates = useCallback(() => {
        // 获取变更后的 state
        const newState = selector(store.getState());
        // 对比前后两次 state
        if (newState !== selectedStateRef.current) {
            forceRender();
        }
    }, [store, selector]);

    // 订阅 state
    useEffect(() => {
        const subscription = store.subscribe(checkForUpdates);
        return () => subscription();
    }, [store, checkForUpdates]);

    // 返回需要的 state
    return selectedStateRef.current;
};

export const useDispatch = () => {
    const store = useContext(MyContext);
    return store.dispatch;
};
